package com.authine.cloudpivot.ext.util;

import com.alibaba.cola.exception.BizException;
import com.authine.cloudpivot.file.res.AttachmentRes;
import com.authine.common.util.IdWorker;
import com.authine.hermes.app.file.feign.FtpFeignServiceI;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

/**
 * @program: gm-market
 * @description: 文件下载工具类
 * @author: wlw
 * @create: 2021-08-12 21:38
 **/
@Slf4j
public class FileUtil {
    private static FtpFeignServiceI ftpFeignServiceI = ApplicationContextUtils.getBean(FtpFeignServiceI.class);


    public static String fileToBase64(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int)file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }

    public static void main(String[] args) {
        try {
            markImageBySingleIcon(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取 文件 流
     * @param url
     * @return
     * @throws IOException
     */
    public static byte[] getFile(String url)   {
        try {
            URL urlConet = new URL(url);
            HttpURLConnection con = (HttpURLConnection)urlConet.openConnection();
            con.setRequestMethod("GET");
            con.setConnectTimeout(4 * 1000);
            InputStream inStream = con .getInputStream();    //通过输入流获取图片数据
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int len = 0;
            while( (len=inStream.read(buffer)) != -1 ){
                outStream.write(buffer, 0, len);
            }
            inStream.close();
            byte[] data =  outStream.toByteArray();
            return data;
        } catch (Exception e) {
            log.error("读取文件流失败,e");
            throw new BizException("读取文件流失败");
        }
    }

    /**
     * 给图片添加单个图片水印、可设置水印图片旋转角度
     * @param degree 水印图片旋转角度，为null表示不旋转
     */
    public static  String markImageBySingleIcon(Integer degree) {
        String result = "添加图片水印出错";
        String icon = "C:\\Users\\LX\\Pictures\\水印.png";
        String source = "C:\\Users\\LX\\Pictures\\1632742475(1).png";
        String output = "\\";
        String imageName = "emg";
        String imageType = "jpg";
        try {
            File file = new File(source);
            File ficon = new File(icon);
            if (!file.isFile()) {
                return source + " 不是一个图片文件!";
            }
            //将icon加载到内存中
            Image ic = ImageIO.read(ficon);
            //icon高度
            int icheight = ic.getHeight(null);
            //将源图片读到内存中
            Image img = ImageIO.read(file);
            //图片宽
            int width = img.getWidth(null);
            //图片高
            int height = img.getHeight(null);
            BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
            //创建一个指定 BufferedImage 的 Graphics2D 对象
            Graphics2D g = bi.createGraphics();
            //x,y轴默认是从0坐标开始
            int x = 0;
            int y = (height/2)-(icheight/2);
            //设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            //呈现一个图像，在绘制前进行从图像空间到用户空间的转换
            g.drawImage(img.getScaledInstance(width,height,Image.SCALE_SMOOTH),0,0,null);
            if (null != degree) {
                //设置水印旋转
                g.rotate(Math.toRadians(degree),(double) bi.getWidth() / 2, (double) bi.getHeight() / 2);
            }
            //水印图象的路径 水印一般为gif或者png的，这样可设置透明度
            FileInputStream inputStream = new FileInputStream(ficon);
            ByteArrayOutputStream waterOutput = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024*4];
            int n = 0;
            while (-1 != (n = inputStream.read(buffer))) {
                waterOutput.write(buffer, 0, n);
            }
            byte[] waterBytes =  waterOutput.toByteArray();
            ImageIcon imgIcon = new ImageIcon(waterBytes);
            //得到Image对象。
            Image con = imgIcon.getImage();
            //透明度，最小值为0，最大值为1
            float clarity = 1f;
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,clarity));
            //表示水印图片的坐标位置(x,y)
            //g.drawImage(con, 300, 220, null);
            g.drawImage(con, x, y, null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            g.dispose();
            File sf = new File(output, imageName+"."+imageType);
            ImageIO.write(bi, imageType, sf); // 保存图片
            result = "图片完成添加Icon水印";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 给图片添加单个图片水印、可设置水印图片旋转角度
     * @param icon 水印图片路径（如：F:/images/icon.png）
     * @param source 没有加水印的图片路径（如：F:/images/6.jpg）
     * @param degree 水印图片旋转角度，为null表示不旋转
     */
    public static  AttachmentRes markImageBySingleIcon(InputStream icon,InputStream source,Integer degree)  {
        String output = "/";
        String imageName = UUID.randomUUID().toString();
        String imageType = "jpg";
        try {
            //File ficon = new File(icon);
            //将icon加载到内存中ImageIO
            Image ic = ImageIO.read(icon);
            //icon高度
            int icheight = ic.getHeight(null);
            //将源图片读到内存中
            Image img = ImageIO.read(source);
            //图片宽
            int width = img.getWidth(null);
            //图片高
            int height = img.getHeight(null);
            BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
            //创建一个指定 BufferedImage 的 Graphics2D 对象
            Graphics2D g = bi.createGraphics();
            //x,y轴默认是从0坐标开始
            int x = 0;
            int y = (height/2)-(icheight/2);
            //设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            //呈现一个图像，在绘制前进行从图像空间到用户空间的转换
            g.drawImage(img.getScaledInstance(width,height,Image.SCALE_SMOOTH),0,0,null);
            if (null != degree) {
                //设置水印旋转
                g.rotate(Math.toRadians(degree),(double) bi.getWidth() / 2, (double) bi.getHeight() / 2);
            }
            //水印图象的路径 水印一般为gif或者png的，这样可设置透明度
            ImageIcon imgIcon = new ImageIcon(ic);
            //得到Image对象。
            Image con = imgIcon.getImage();
            //透明度，最小值为0，最大值为1
            float clarity = 1f;
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,clarity));
            //表示水印图片的坐标位置(x,y)
            //g.drawImage(con, 300, 220, null);
            g.drawImage(con, x, y, null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            g.dispose();
            File sf = new File(output, imageName+"."+imageType);
            ImageIO.write(bi, imageType, sf); // 保存图片
            FileInputStream fileInputStream = new FileInputStream(sf);
            ByteArrayOutputStream waterOutput = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024*4];
            int n = 0;
            while (-1 != (n = fileInputStream.read(buffer))) {
                waterOutput.write(buffer, 0, n);
            }
            byte[] waterBytes =  waterOutput.toByteArray();
            MultipartFile multipartFile = new MockMultipartFile("file", IdWorker.nextId() + ".jpg", "text/plain",waterBytes);
            fileInputStream.close();
            sf.delete();
            return ftpFeignServiceI.uploadAttachment(multipartFile).getData();
        } catch (Exception e) {
            log.error("处理图片水印异常：",e);
        }
        return null;
    }
}
